package com.example.photography.fragment.home;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.widget.AbsListView;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.photography.R;
import com.example.photography.adapter.home_vlog.VlogAdapter;
import com.example.photography.bean.Vlog;
import com.example.photography.common.AppNetConfig;
import com.example.photography.common.BaseFragment;
import com.example.photography.util.UIUtils;
import com.example.photography.util.Util;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import com.scwang.smart.refresh.footer.BallPulseFooter;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.constant.SpinnerStyle;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.shuyu.gsyvideoplayer.GSYVideoManager;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cz.msebera.android.httpclient.Header;

public class Home_vlog extends BaseFragment {
    @BindView(R.id.lv_vlog)
    ListView lvVlog;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private List<Vlog> vlogs;
    private boolean sign;
    private VlogAdapter productAdapter;

    @Override
    protected RequestParams getParams() {
        return null;
    }

    @Override
    protected String getUrl() {
        return AppNetConfig.vlog;
    }

    @Override
    protected void initData(String content) {
        JSONObject jsonObject = JSON.parseObject(content);
        int status = jsonObject.getInteger("status");
        if (status == 202){
            String data = jsonObject.getString("data");
            //获取集合数据
            vlogs = new ArrayList<>();
            vlogs = JSON.parseArray(data, Vlog.class);
            //装载适配器
            productAdapter = new VlogAdapter(vlogs,getActivity());
            lvVlog.setAdapter(productAdapter);//显示列表
        }else {
            Util.show(getActivity(),"获取数据失败~");
        }

        /**
         * 下拉刷新
         */
        refreshLayout.setRefreshHeader(new ClassicsHeader(UIUtils.getContext()));
        refreshLayout.setRefreshFooter(new ClassicsFooter(UIUtils.getContext()));
        //设置 Footer 为 球脉冲 样式
        refreshLayout.setRefreshFooter(new BallPulseFooter(UIUtils.getContext()).setSpinnerStyle(SpinnerStyle.Scale));
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
//                Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
//                    @Override
//                    public void run() {
//
//                    }
//                });
                sign = false;
                sendAsyncHttpClient();
                UIUtils.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //todo 有时刷新失败
                        refreshlayout.finishRefresh(sign);//传入false表示刷新失败
                    }
                },2000);

            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });

        lvVlog.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            // TODO: 2021/3/21 滑动很多视频播放才停止
            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                int lastVisibleItem = firstVisibleItem + visibleItemCount;
                //大于0说明有播放
                if (GSYVideoManager.instance().getPlayPosition() >= 0) {
                    //当前播放的位置
                    int position = GSYVideoManager.instance().getPlayPosition();
                    //对应的播放列表TAG
                    if (GSYVideoManager.instance().getPlayTag().equals(VlogAdapter.TAG)
                            && (position < firstVisibleItem || position > lastVisibleItem)) {
                        if (GSYVideoManager.isFullState(getActivity())) {
                            return;
                        }
                        //如果滑出去了上面和下面就是否，和今日头条一样
                        GSYVideoManager.releaseAllVideos();
                        productAdapter.notifyDataSetChanged();
                    }
                }
            }
        });

    }

    private void sendAsyncHttpClient() {
        UIUtils.getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                AsyncHttpClient client = new AsyncHttpClient();
                client.post(AppNetConfig.vlog, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                        //解析json数据
                        String jsonData = new String(responseBody);
                        try {
                            if (!jsonData.equals("")){
                                org.json.JSONObject jsonObject = new org.json.JSONObject(jsonData);
                                String data = jsonObject.getString("data");
                                //获取集合数据
                                vlogs = new ArrayList<>();
                                vlogs = JSON.parseArray(data, Vlog.class);
                                handler.sendEmptyMessageDelayed(1, 0);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Util.show(getActivity(),e.toString());
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                        Util.show(getActivity(),"网络请求失败~");
                    }
                });
            }
        }, 0);


    }


    @SuppressLint("HandlerLeak")
    android.os.Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    sign = true;
                    //刷新适配器
                    productAdapter.refresh(vlogs);
                    break;
            }
        }
    };
    @Override
    public int getLayoutId() {
        return R.layout.home_vlog;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //移除所有的未被执行的消息
        handler.removeCallbacksAndMessages(null);
        GSYVideoManager.releaseAllVideos();
    }



    @Override
    public void onResume() {
        super.onResume();
        GSYVideoManager.onResume();

    }

    @Override
    public void onStop() {
        super.onStop();
        GSYVideoManager.releaseAllVideos();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            //隐藏时所作的事情
            GSYVideoManager.releaseAllVideos();
        } else {
            //显示时所作的事情
            GSYVideoManager.onResume();

        }
    }
}
